package com.hqyj.controller;

import com.hqyj.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Random;

@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    EmailUtil emailUtil;

    //发送验证码
    @RequestMapping("/sendCode")
    public HashMap<String, Object> sendCode(String email, HttpSession session) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //随机对象
        Random rd = new Random();
        int code = rd.nextInt(9000) + 1000;

        String info = emailUtil.sendEmail(email, "XX酒店", "你的验证码是" + code + ",此验证码10分钟后失效！");
        if (info.equals("success")) {
            map.put("info", "验证码发送成功");
            session.setAttribute("code", code);
            session.setMaxInactiveInterval(60000);
        } else {
            map.put("info", "请输入可以使用的邮箱！");
        }
        return map;
    }

    //验证码
    @RequestMapping("/checkCode")
    public HashMap<String, Object> emailLogin(String code, HttpSession session) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        String sessionCode = session.getAttribute("code") + "";
        System.out.println(sessionCode);
        if (code.equals(sessionCode)) {
            map.put("info", "验证成功");
            session.removeAttribute("code");
        } else {
            map.put("info", "验证码错误");
        }
        return map;
    }
}
